package com.portal.gateway.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.portal.common.core.web.domain.AjaxResult;
import com.portal.gateway.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WeatherServiceImpl implements WeatherService {
    // 参考https://www.sojson.com/api/weather.html
    @Value("${weather.api.url:http://t.weather.sojson.com/api/weather/city/101270101}")
    private String weatherApiUrl;
    @Override
    public AjaxResult getWeather(String ip) {
        if (ip == null || ip.isEmpty()) {
            log.warn("Invalid IP address provided: {}", ip);
            return AjaxResult.error("Invalid IP address");
        }

        try {
            HttpResponse response = HttpRequest.get(weatherApiUrl)
                    .execute();

            if (response.isOk()) {
                JSONObject jsonObject = JSONUtil.parseObj(response.body());
                JSONObject data = jsonObject.getJSONObject("data");
                Object weatherData = data.get("forecast");

                log.info("Weather data for IP {}: {}", ip, weatherData);

                if (weatherData != null) {
                    return AjaxResult.success(weatherData);
                } else {
                    log.error("Failed to fetch weather data for IP {}: No forecast data found", ip);
                    return AjaxResult.error("Failed to fetch weather data");
                }
            } else {
                log.error("Failed to fetch weather data for IP {}: HTTP error code {}", ip, response.getStatus());
                return AjaxResult.error("Failed to fetch weather data");
            }
        } catch (Exception e) {
            log.error("Failed to fetch weather data for IP {}: Exception occurred", ip, e);
            return AjaxResult.error("Failed to fetch weather data");
        }
    }
}
